function varargout = Shell_FY13_v001(varargin)
% SHELL_STRUCT_PSD_TXF Application M-file for shell_struct_psd_txf.fig
%    FIG = SHELL_STRUCT_PSD_TXF launch shell_struct_psd_txf GUI.
%    SHELL_STRUCT_PSD_TXF('callback_name', ...) invoke the named callback.

% Last Modified by GUIDE v2.5 17-Jun-2013 20:32:36
%
%  Modified 3/14/05 by B. Ross
%  Changed the printing logic to correlate with logic changes in GDASPlot
%  routine.
%
%  Modified 4/11/05 by B. Ross
%  Added a submenu item to export an analysis only Project file.
%
%  Modified 4/22/05 by B. Ross
%  Pulled the logic to set plot scales from GDADSPlot to the file_print_Callback
%  function.  Added the option of plotting using either an autoscaled X & Y axes
%  or manually scaled X & Y axes.  The scaling logic is basically the logic D.
%  Baker had in the GDADSPlot routine.  The same X & Y scales are used for all
%  channels in the print batch.
%  Tweaked the process of setting manual scales.  Now provide max/min values
%  from the data to help user select manual scale values.
%
if nargin == 0  % LAUNCH GUI

    fig = openfig(mfilename,'reuse');

    % Resize the Application Window to fill the Screen
    set(fig, 'Units', 'pixels');
    s = get(0, 'ScreenSize');
    AppScreen = [2 20 (s(3)-4) (s(4)-55)];
    set(fig, 'Position', AppScreen);
    % get(fig)

    % Generate a structure of handles to pass to callbacks, and store it. 
	handles = guihandles(fig);
	guidata(fig, handles);

	if nargout > 0
		varargout{1} = fig;
	end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

	try
		if (nargout)
			[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
		else
			feval(varargin{:}); % FEVAL switchyard
		end
	catch
		disp(lasterr);
	end

end

% =========================================================================
function varargout = psd_pushbutton_Callback(h, eventdata, handles, varargin)
gsfc_psd2(handles.first, handles.last, handles.CurrentDataset);
%length(Project.Test_Item.Run.Channel(1).Analysis)  %just for checking
handles.type = 2;
guidata(h, handles);
plot_onscreen_PSD(h, eventdata, handles, varargin);

% =========================================================================
function varargout = txf_pushbutton_Callback(h, eventdata, handles, varargin)
handles.ref_chan = gsfc_txf2(handles.first, handles.last, handles.CurrentDataset);
%length(Project.Test_Item.Run.Channel(1).Analysis)  %just for checking
handles.type = 3;
guidata(h, handles);
plot_onscreen_FRF(h, eventdata, handles, varargin);

% =========================================================================
function varargout = sine_pushbutton_Callback(h, eventdata, handles, varargin)
global Project;
% JWST_Preprocessing(27);
sineswp022;
% JWST_Postprocessing(27, 36);
% Comment out the following lines to return to normal processing
% Total Moment Frequency Calculation
% TotalMoment = ...
%     sqrt(double(Project.Test_Item.Run.Channel(132).Analysis(handles.CurrentDataset).Ord).^2 + ...
%     double(Project.Test_Item.Run.Channel(133).Analysis(handles.CurrentDataset).Ord).^2);
% Project.Test_Item.Run.Channel(134).Analysis(handles.CurrentDataset).Ord =  single(TotalMoment);
% End of Total Moment Frequency Calculation
handles.type = 4;
guidata(h, handles);
plot_onscreen_sine(h, eventdata, handles, varargin);

% =========================================================================
function varargout = Sine_FRF_Callback(h, eventdata, handles, varargin)
handles.ref_chan = sinefrf02;
handles.type = 5;
guidata(h, handles);
plot_onscreen_Sine_FRF(h, eventdata, handles, varargin);

% =========================================================================
function varargout = shock_pushbutton_Callback(h, eventdata, handles, varargin)
% shock_smallwood(handles.first, handles.last, handles.CurrentDataset);
% Added on 26-Aug-2010 by Chris McLeod to provide 1/12 octave freq spacing
shock_smallwood_cm(handles.first, handles.last, handles.CurrentDataset);
handles.type = 6;
guidata(h, handles);
plot_onscreen_shockmag(h, eventdata, handles, varargin);

% =========================================================================
function varargout = Octave_pushbutton_Callback(h, eventdata, handles, varargin)
Acoustic3rdOctave_v03(handles.first, handles.last, handles.CurrentDataset);
handles.type = 7;
guidata(h, handles); % Save the changes
plot_onscreen_Octave(h, eventdata, handles, varargin);
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = custom_analysis_pushbutton_Callback(h, eventdata, handles, varargin)
% helpdlg('No Custom Analysis currently available','Custom Analysis');

LowPassFilter;  % call Dan's low pass filter routine

% prompt = {'Source: STI / DataMAX'};
% dlgTitle = 'Source';
% lineNo = [1 60];
% defAns = {'DataMAX'};
% Ans = inputdlg(prompt, dlgTitle, lineNo, defAns);
% source = upper(Ans{1,1});
% switch source
%     case {'STI'}
%         ForceRingCal_v08;
%     case {'DATAMAX'}
%         Rescale;
%     otherwise
%         errordlg('The only correct response is STI or DataMAX.','Incorrect Entry');
% end
guidata(h, handles);

% =========================================================================
function varargout = first_chan_pushbutton_Callback(h, eventdata, handles, varargin)
handles.chan = 1;
guidata(h, handles); % Save the changes
choose_plot(h, eventdata, handles, varargin);
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = previous_chan_pushbutton_Callback(h, eventdata, handles, varargin)
if handles.chan ~= 1
   handles.chan = handles.chan - 1;
end

choose_plot(h, eventdata, handles, varargin);
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = next_channel_pushbutton_Callback(h, eventdata, handles, varargin)
global Project;
if handles.chan ~= Project.Test_Item.Run.Num_Chan;
   handles.chan = handles.chan + 1;
end
choose_plot(h, eventdata, handles, varargin);
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = last_channel_pushbutton_Callback(h, eventdata, handles, varargin)
global Project;
handles.chan = Project.Test_Item.Run.Num_Chan;
choose_plot(h, eventdata, handles, varargin);
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = goto_channel_edit_Callback(h, eventdata, handles, varargin)
global Project;
user_entry = str2num(get(h, 'string'));
if user_entry < 1 || user_entry > Project.Test_Item.Run.Num_Chan;
    errordlg('Not Valid Channel Number');
else
    handles.chan = user_entry;
    guidata(h, handles);
    choose_plot(h, eventdata, handles, varargin);
end

% =========================================================================
function varargout = file_menu_Callback(h, eventdata, handles, varargin)

% =========================================================================
function varargout = file_open_submenu_Callback(h, eventdata, handles, varargin)
global Project;
% Change position to C:\Data directory
filepath = 'C:\\Data';
% Construct the cd command 
filepath = ['cd ' '''' filepath ''''];
eval(filepath);
[filename, pathname] = uigetfile('*.mat', 'MATLAB Data Files');
if isequal([filename, pathname], [0,0])
    return
else
    File = fullfile(pathname, filename);
    handles.pathname = pathname;
    Project = importdata(File);
end
handles.type = 1;
handles.first = 1;
handles.last  = size(Project.Test_Item.Run.Time_Ref,2);
guidata(h, handles); % Save the changes
%Determine next available Dataset
handles.CurrentDataset = Dataset(handles);
guidata(h, handles); % Save the changes
first_chan_pushbutton_Callback(h, eventdata, handles, varargin);

% =========================================================================
function varargout = file_save_as_submenu_Callback(h, eventdata, handles, varargin)
global Project;
pathname = handles.pathname;
% Save the Current Directory
CurDir = pwd;
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to original data directory
% Remove the last '\'
pathname(length(pathname)) = '';
% Change every '\' to an escape sequence '\\'
filepath = strrep(pathname,'\','\\');
% Construct the cd command 
filepath = ['cd ' '''' filepath ''''];
eval(filepath);
%- - - - - - - - - - - - - - - - - - - - - - - -
% - - - From Dan Worth's code - - -
[filename, pathname] = uiputfile('*.mat', 'MATLAB Data Files');
if isequal([filename, pathname], [0,0])
    disp('File not found')
else
    File = fullfile(pathname, filename);
    save( File, 'Project' );
end
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to Current Directory
% Change every '\' to an escape sequence '\\'
CurrentPath = strrep(CurDir,'\','\\');
% Construct the cd command 
CurrentPath = ['cd ' '''' CurrentPath ''''];
eval(CurrentPath);

% =========================================================================
function varargout = file_convert_submenu_Callback(h, eventdata, handles, varargin)
global Project;
Project = EmptyProj;
% pack;
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to C:\Data directory
filepath = 'C:\\Data';
% Construct the cd command 
filepath = ['cd ' '''' filepath ''''];
eval(filepath);
[filename, pathname] = uigetfile('*.VDF', 'Vamp Data Files');
if isequal([filename, pathname], [0,0])
    return
else
    fullname = fullfile(pathname,filename);
    handles.pathname = pathname;
    File = strtok(fullname, '.');
    Project = Build_Struct_v63(File);
end
%- - - - - - - - - - - - - - - - - - - - - - - -
% Remove the Y-Axis offset
for index = 1:Project.Test_Item.Run.Num_Chan
   Project.Test_Item.Run.Channel(index).Time_His = Project.Test_Item.Run.Channel(index).Time_His - mean(Project.Test_Item.Run.Channel(index).Time_His);
end
%- - - - - - - - - - - - - - - - - - - - - - - -
handles.type = 1;
handles.first = 1;
handles.last  = size(Project.Test_Item.Run.Time_Ref,2);
guidata(h, handles); % Save the changes
%Determine next available Dataset
handles.CurrentDataset = Dataset(handles);
guidata(h, handles); % Save the changes
first_chan_pushbutton_Callback(h, eventdata, handles, varargin);

% =========================================================================
 function file_convert_DataMAX_submenu_Callback(hObject, eventdata, handles, varargin)
% hObject    handle to file_convert_DataMAX_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global Project;
Project = EmptyProj;
% pack;
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to C:\Data directory
filepath = 'C:\\Data';
% Construct the cd command 
filepath = ['cd ' '''' filepath ''''];
eval(filepath);
[filename, pathname] = uigetfile('*.*', 'DataMAX Data Files');
if isequal([filename, pathname], [0,0])
    return
else
    fullname = fullfile(pathname,filename);
    handles.pathname = pathname;
%    File = strtok(fullname, '.');
    File = fullname;
    Project = Build_Struct_DataMAX_v27(File);
end
%- - - - - - - - - - - - - - - - - - - - - - - -
%ask for Analysis Description
prompt = {'Project Name', 'Test Item', 'WD', 'Run Axis', 'Test Type', 'Test Level', 'Run Number', 'Run Description','Remove DC Offset'};
dlgTitle = 'Test Info';
lineNo = [1 60; 1 60; 1 12; 1 4; 1 12; 1 15; 1 12; 1 60; 1 30];
load 'C:\Data\AppDefaults\defPrompt';
Ans = inputdlg(prompt, dlgTitle, lineNo, defAns);
Project.Name = Ans{1,1};
Project.Test_Item.TI_Name = Ans{2,1};
Project.Test_Item.WD = str2num(Ans{3,1});
Project.Test_Item.Run.Axis = Ans{4,1};
Project.Test_Item.Run.Test_Type = Ans{5,1};
Project.Test_Item.Run.Test_Level = Ans{6,1};
Project.Test_Item.Run.Run_Num = str2num(Ans{7,1});
Project.Test_Item.Run.Descrip = Ans{8,1};
defAns{1,1} = Ans{1,1};
defAns{1,2} = Ans{2,1};
defAns{1,3} = Ans{3,1};
defAns{1,4} = Ans{4,1};
defAns{1,5} = Ans{5,1};
defAns{1,6} = Ans{6,1};
defAns{1,7} = Ans{7,1};
defAns{1,8} = Ans{8,1};
defAns{1,9} = Ans{9,1};
save 'C:\Data\AppDefaults\defPrompt.mat' defAns;
%- - - - - - - - - - - - - - - - - - - - - - - -
if (strcmp(upper(Ans{9,1}), 'YES')) || (strcmp(upper(Ans{9,1}), 'Y'))
   % Remove the Y-Axis offset
   for index = 1:Project.Test_Item.Run.Num_Chan
      Project.Test_Item.Run.Channel(index).Time_His = ...
         Project.Test_Item.Run.Channel(index).Time_His - mean(Project.Test_Item.Run.Channel(index).Time_His);
   end
else
   fprintf('DC not removed\n');
end

%- - - - - - - - - - - - - - - - - - - - - - - -
% Rescale the data to convert from Volts to Engineering Units (i.e. G's,
% PSI, microstrain, etc.
RescaleDynaWorks;
% JWST_MIRI_SHIELD_Strain_Force_Calcs;
% GPM_Obs_Mass_Sim_Force;
% Build_Virtual_Pressure(41);
% Force_Cal_v08;
% Build_Virtual_TimeHistory(71);
%Strain_Avg_v01;
% ForceConfig_LRO;
% Moment_Cal_v04; % Added for TIRS Sensor Unit WD 60472 | 10-Nov-2011
%- - - - - - - - - - - - - - - - - - - - - - - -
handles.type = 1;
handles.first = 1;
handles.last  = size(Project.Test_Item.Run.Time_Ref,2);
% guidata(h, handles); % Save the changes
guidata(hObject, handles); % Save the changes
%Determine next available Dataset
handles.CurrentDataset = Dataset(handles);
% guidata(h, handles); % Save the changes
guidata(hObject, handles); % Save the changes
% first_chan_pushbutton_Callback(h, eventdata, handles, varargin);
first_chan_pushbutton_Callback(hObject, eventdata, handles, varargin);

% =========================================================================
function varargout = file_restore_submenu_Callback(h, eventdata, handles, varargin)
global Project;
handles.type = 1;
handles.first = 1;
handles.last  = size(Project.Test_Item.Run.Time_Ref,2);
guidata(h, handles); % Save the changes
% %Determine next available Dataset
% handles.CurrentDataset = Dataset(handles);
% guidata(h, handles); % Save the changes

first_chan_pushbutton_Callback(h, eventdata, handles, varargin);

% =========================================================================
function varargout = file_print_submenu_Callback(h, eventdata, handles, varargin)
global Project;
[print_data_type,anal_num,print_chan_start,print_chan_end,PlotXScaleFlag,PlotYScaleFlag,...
        status] = print_data_select;
%  Check to see if user has cancelled operation
if strcmp(status,'cancel')
    return
end
%  Check the channel number selections to make sure they are in the range of the
%  dataset.
if print_chan_start < 0; print_chan_start = 1;end;
if print_chan_start > Project.Test_Item.Run.Num_Chan;
    print_chan_start = Project.Test_Item.Run.Num_Chan;
end
if print_chan_end > Project.Test_Item.Run.Num_Chan
    print_chan_end = Project.Test_Item.Run.Num_Chan;
end
if print_chan_end < print_chan_start
	print_chan_end = print_chan_start;
end
%- - - - - - - - - - - - - - - - - - - - - - - -
%  If using manual scaling, prompt for values
if (PlotXScaleFlag == 1 || PlotYScaleFlag == 1)
    switch print_data_type
        case {0, 1} % Time History
            XRange = [Project.Test_Item.Run.Time_Ref(handles.first) Project.Test_Item.Run.Time_Ref(handles.last)];
            THstart = 1;
            THend = length(Project.Test_Item.Run.Channel(print_chan_start).Time_His);
            [ymin, ymax] = TimeHisMinMax(print_chan_start, print_chan_end, THstart, THend);
            YRange = [ymin ymax];
        case {2, 3} % Analysis or Time History and Analysis
            XRange = [Project.Test_Item.Run.Channel(1).Analysis(anal_num).Abs(1) Project.Test_Item.Run.Low_Pass];
            y = zeros(length(Project.Test_Item.Run.Channel(1).Analysis(anal_num).Ord), print_chan_end);
            for i = print_chan_start:print_chan_end;
                y(:,i) = abs(Project.Test_Item.Run.Channel(i).Analysis(anal_num).Ord'); % Handles real or complex data
            end
            YRange = [min(min(y)) max(max(y))];
            clear y;
    end       
	[XManualScale,YManualScale,status] = SelectManualScales(PlotXScaleFlag, PlotYScaleFlag,XRange,YRange,print_data_type);
	%  Check to see if user has cancelled operation
	if strcmp(status,'cancel')
        return
	end
end

%  Set the X and Y axes scales for the plots
% Standard Time History scale values
THMaxPlotScaleArray=[.0001 .0002 .0005 .001 .002 .005 .01 .02 .05 .1 .2 .5 1.0 2.0 5.0 10.0 20.0 50.0 100.0 200.0 ...
        500.0 1000.0 2000.0 5000.0 10000.0 20000.0 50000.0 100000.0 200000.0 500000.0 1000000.0 2000000.0 10000000.0 ...
        20000000.0 100000000.0];
% Standard Analysis scale values
AnMaxPlotScaleArray=[1e-16 1e-15 1e-14 1e-13 1e-12 1e-11 1e-10 1e-9 1e-8 1e-7 ...
        1e-6 1e-5 1e-4 1e-3 1e-2 1e-1 1 1e1 1e2 1e3 1e4 1e5 1e6 1e7 1e8 ...
        1e9 1e10 1e11 1e12 1e13 1e14 1e15 1e16 1e17 1e18 1e19 1e20];

if (PlotXScaleFlag == 1 && PlotYScaleFlag == 1) %  Manual scale for both X and Y axes
	XScale = XManualScale;
	YScale = YManualScale;
	if print_data_type == 3 % Time History and Analysis
		% Set time history X Axis max and min based on analyzed time history segment for
		% corresponding analysis.
		THstart = Project.Test_Item.Run.Channel(1).Analysis(anal_num).FPoint;
		THend = Project.Test_Item.Run.Channel(1).Analysis(anal_num).LPoint;
		THXmin = THstart/Project.Test_Item.Run.Sample_Rate;
		THXmax = THend/Project.Test_Item.Run.Sample_Rate;
		THXScale = [THXmin, THXmax];
		%  Autoscale the Y axis for Time History plots
		[thistmin, thistmax] = TimeHisMinMax(print_chan_start, print_chan_end, THstart, THend);
		if thistmax >= abs(thistmin)
			thistmin = -1*thistmax;
		elseif thistmax < abs(thistmin)
			thistmax = -1*thistmin;
		end
		%  Using max value pick a standard scale 
		PlotRangeRem = rem(thistmax, THMaxPlotScaleArray);
		PlotRangeIndex = find(PlotRangeRem == thistmax);
		THYScale = [-1*THMaxPlotScaleArray(PlotRangeIndex(1)) THMaxPlotScaleArray(PlotRangeIndex(1))];
	end
	% ********************************************************************************
	% ******* Might need to put some checks in for scale values, ie no negative values
	% ******* for functions that will plot on a log scale. *****************
	% ********************************************************************************
elseif (PlotXScaleFlag == 1 && PlotYScaleFlag == 0) % Manual scale X axis and autoscale Y axis
    XScale = XManualScale;
    %  Determine the Y Scale
    switch print_data_type
        case {0, 1} % Time History
            %  Find the max and min values of all the channels
            THstart = 1;
            THend = length(Project.Test_Item.Run.Channel(print_chan_start).Time_His);
			[ymin, ymax] = TimeHisMinMax(print_chan_start, print_chan_end, THstart, THend);
            if ymax >= abs(ymin)
                ymin = -1*ymax;
            elseif ymax < abs(ymin)
                ymax = -1*ymin;
            end
            %  Using max value pick a standard scale 
            PlotRangeRem = rem(ymax, THMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == ymax);
            YScale = [-1*THMaxPlotScaleArray(PlotRangeIndex(1)) THMaxPlotScaleArray(PlotRangeIndex(1))];
        case 2 % Analysis
            %  Find the max and min values of all the channels
            for i = print_chan_start:print_chan_end;
                y(:,i) = abs(Project.Test_Item.Run.Channel(i).Analysis(anal_num).Ord'); % Handles real or complex data
            end
            ymax = max(max(y));
            % ymin = min(min(y));
            clear y;
            %  Using max value pick a standard scale
            PlotRangeRem = rem(ymax, AnMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == ymax);
            if PlotRangeIndex(1) <= 5; PlotRangeIndex(1) = 6; end; %  Keep scale within standard range values
            YScale = [AnMaxPlotScaleArray(PlotRangeIndex(1)-5) AnMaxPlotScaleArray(PlotRangeIndex(1)+1)]; % 6 Decades
        case 3 % Time History and Analysis
            % Set Time History X Axis max and min based on analyzed time history segment for
            % corresponding analysis.
            THstart = Project.Test_Item.Run.Channel(1).Analysis(anal_num).FPoint;
            THend = Project.Test_Item.Run.Channel(1).Analysis(anal_num).LPoint;
            THXmin = THstart/Project.Test_Item.Run.Sample_Rate;
            THXmax = THend/Project.Test_Item.Run.Sample_Rate;
            THXScale = [THXmin, THXmax];
            %  Autoscale the Y axis for Time History plots
			[thistmin, thistmax] = TimeHisMinMax(print_chan_start, print_chan_end, THstart, THend);
            if thistmax >= abs(thistmin)
                thistmin = -1*thistmax;
            elseif thistmax < abs(thistmin)
                thistmax = -1*thistmin;
            end
            %  Using max value pick a standard scale 
            PlotRangeRem = rem(thistmax, THMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == thistmax);
            THYScale = [-1*THMaxPlotScaleArray(PlotRangeIndex(1)) THMaxPlotScaleArray(PlotRangeIndex(1))];
            
            %  Find the Analysis max and min values of all the channels
            for i = print_chan_start:print_chan_end;
                y(:,i) = abs(Project.Test_Item.Run.Channel(i).Analysis(anal_num).Ord'); % Handles real or complex data
            end
            ymax = max(max(y));
            ymin = min(min(y));
            clear y;
            %  Using max value pick a standard scale
            PlotRangeRem = rem(ymax, AnMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == ymax);
            if PlotRangeIndex(1) <= 5; PlotRangeIndex(1) = 6; end; %  Keep scale within standard range values
            YScale = [AnMaxPlotScaleArray(PlotRangeIndex(1)-5) AnMaxPlotScaleArray(PlotRangeIndex(1)+1)]; % 6 Decades
    end
elseif (PlotXScaleFlag == 0 && PlotYScaleFlag == 1) % Autoscale X axis and manual scale Y axis
    YScale = YManualScale;
    %  Determine the X Scale
    switch print_data_type
        case {0, 1} % Time History
            XScale = [Project.Test_Item.Run.Time_Ref(handles.first) Project.Test_Item.Run.Time_Ref(handles.last)];
        case 2 % Analysis
            Xmin = Project.Test_Item.Run.Channel(1).Analysis(anal_num).Abs(1);
            if Xmin < 1 % Since using log scale do not round to zero
                temp = num2str(Xmin, '%5.3e');
                Xmin = floor(str2num(temp(1:4)))/(10^str2num(temp(8:10)));
            else
                Xmin = floor(Xmin);
            end
            XScale = [Xmin Project.Test_Item.Run.Low_Pass];
        case 3 % Time History and Analysis
            % Set Time History X Axis max and min based on analyzed time history segment for
            % corresponding analysis.
            THstart = Project.Test_Item.Run.Channel(1).Analysis(anal_num).FPoint;
            THend = Project.Test_Item.Run.Channel(1).Analysis(anal_num).LPoint;
            THXmin = THstart/Project.Test_Item.Run.Sample_Rate;
            THXmax = THend/Project.Test_Item.Run.Sample_Rate;
            THXScale = [THXmin, THXmax];
            %  Autoscale the Y axis for Time History plots
			[thistmin, thistmax] = TimeHisMinMax(print_chan_start, print_chan_end, THstart, THend);
            if thistmax >= abs(thistmin)
                thistmin = -1*thistmax;
            elseif thistmax < abs(thistmin)
                thistmax = -1*thistmin;
            end
            %  Using max value pick a standard scale 
            PlotRangeRem = rem(thistmax, THMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == thistmax);
            THYScale = [-1*THMaxPlotScaleArray(PlotRangeIndex(1)) THMaxPlotScaleArray(PlotRangeIndex(1))];
            
            % Determine Analysis X Scale
            Xmin = Project.Test_Item.Run.Channel(1).Analysis(anal_num).Abs(1);
            if Xmin < 1 % Since using log scale do not round to zero
                temp = num2str(Xmin, '%5.3e');
                Xmin = floor(str2num(temp(1:4)))/(10^str2num(temp(8:10)));
            else
                Xmin = floor(Xmin);
            end
            XScale = [Xmin Project.Test_Item.Run.Low_Pass];
    end
elseif (PlotXScaleFlag == 0 && PlotYScaleFlag == 0) % Autoscale both X and Y axes
    %  Determine the X Scale
    switch print_data_type
        case {0, 1} % Time History
            XScale = [Project.Test_Item.Run.Time_Ref(handles.first) Project.Test_Item.Run.Time_Ref(handles.last)];
        case 2 % Analysis
            Xmin = Project.Test_Item.Run.Channel(1).Analysis(anal_num).Abs(1);
            if Xmin < 1 % Since using log scale do not round to zero
                temp = num2str(Xmin, '%5.3e');
                Xmin = floor(str2num(temp(1:4)))/(10^str2num(temp(8:10)));
            else
                Xmin = floor(Xmin);
            end
            XScale = [Xmin Project.Test_Item.Run.Low_Pass];
        case 3 % Time History and Analysis
            % Set Time History X Axis max and min based on analyzed time history segment for
            % corresponding analysis.
            THstart = Project.Test_Item.Run.Channel(1).Analysis(anal_num).FPoint;
            THend = Project.Test_Item.Run.Channel(1).Analysis(anal_num).LPoint;
            THXmin = THstart/Project.Test_Item.Run.Sample_Rate;
            THXmax = THend/Project.Test_Item.Run.Sample_Rate;
            THXScale = [THXmin, THXmax];
            %  Determine Analysis X Scale
            Xmin = Project.Test_Item.Run.Channel(1).Analysis(anal_num).Abs(1);
            if Xmin < 1 % Since using log scale do not round to zero
                temp = num2str(Xmin, '%5.3e');
                Xmin = floor(str2num(temp(1:4)))/(10^str2num(temp(8:10)));
            else
                Xmin = floor(Xmin);
            end
            XScale = [Xmin Project.Test_Item.Run.Low_Pass];
    end
    %  Determine the Y Scale
    switch print_data_type
        case {0, 1} % Time History
            %  Find the max and min values of all the channels
			[ymin, ymax] = TimeHisMinMax(print_chan_start, print_chan_end, handles.first, handles.last);
            if ymax >= abs(ymin)
                ymin = -1*ymax;
            elseif ymax < abs(ymin)
                ymax = -1*ymin;
            end
            %  Using max value pick a standard scale 
            PlotRangeRem = rem(ymax, THMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == ymax);
            YScale = [-1*THMaxPlotScaleArray(PlotRangeIndex(1)) THMaxPlotScaleArray(PlotRangeIndex(1))];
        case 2  % Analysis
        case 3  % Time History and Analysis
            %  Autoscale the Y axis for Time History plots
			[thistmin, thistmax] = TimeHisMinMax(print_chan_start, print_chan_end, THstart, THend);
            if thistmax >= abs(thistmin)
                thistmin = -1*thistmax;
            elseif thistmax < abs(thistmin)
                thistmax = -1*thistmin;
            end
            %  Using max value pick a standard scale 
            PlotRangeRem = rem(thistmax, THMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == thistmax);
            THYScale = [-1*THMaxPlotScaleArray(PlotRangeIndex(1)) THMaxPlotScaleArray(PlotRangeIndex(1))];
            %  Determine the Analysis Y Scale
            for i = print_chan_start:print_chan_end;
                y(:,i) = abs(Project.Test_Item.Run.Channel(i).Analysis(anal_num).Ord'); % Handles real or complex data
            end
            ymax = max(max(y));
            ymin = min(min(y));
            clear y;
            %  Using max value pick a standard scale
            PlotRangeRem = rem(ymax, AnMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == ymax);
            if PlotRangeIndex(1) <= 5; PlotRangeIndex(1) = 6; end; %  Keep scale within standard range values
            YScale = [AnMaxPlotScaleArray(PlotRangeIndex(1)-5) AnMaxPlotScaleArray(PlotRangeIndex(1)+1)]; % 6 Decades
    end
end  % Setting X and Y axes Scales
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Set directory and filename for Postscript and PDF's
[pdffilename, pdfpathname, pdffilterindex] = uiputfile('*.pdf', 'Save PDF...');
if pdffilterindex == 0
    return
end
%- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
%  Cycle through all channels, create Postscript file that can be printed using
%  the separate program, PrintFile.
for index= print_chan_start:print_chan_end;
    tmpstr = num2str(index);
    xlab = strcat('Channel No.',tmpstr);
	switch print_data_type
        case {0, 1} % Time History
            GDADSplot(index,anal_num,0,XScale,YScale);    
        case 2 % Analysis
				% This section was added on 19-Sep-2005 by C.McLeod to override the Y-Axis autoscale mode that sets
				% the Y-Axis scale the same for all of the plots. The previous mode of operation often made it necessay
				% to break the range of channels into smaller sections in order to optimize the appearence of the plot.
            y = abs(Project.Test_Item.Run.Channel(index).Analysis(anal_num).Ord'); % Handles real or complex data
            ymax = max(y);
            ymin = min(y);
            % Using max value pick a standard scale
            PlotRangeRem = rem(ymax, AnMaxPlotScaleArray);
            PlotRangeIndex = find(PlotRangeRem == ymax);
            if PlotRangeIndex(1) <= 5; PlotRangeIndex(1) = 6; end; %  Keep scale within standard range values
            YScale = [AnMaxPlotScaleArray(PlotRangeIndex(1)-5) AnMaxPlotScaleArray(PlotRangeIndex(1)+1)]; % 6 Decades
            GDADSplot(index,anal_num,Project.Test_Item.Run.Channel(index).Analysis(anal_num).Type,XScale,YScale);
        case 3 % Both Analysis and Time History
            GDADSplot(index,anal_num,0,THXScale,THYScale);
            if index == print_chan_start
                PlotHandle = gcf;
                eval(['print ''' pdfpathname pdffilename(1:end-3) 'ps'' -dpsc -f' num2str(PlotHandle)])
            else
                PlotHandle = gcf;
                eval(['print ''' pdfpathname pdffilename(1:end-3) 'ps'' -dpsc -append -f' num2str(PlotHandle)])
            end
            close %close figure
            GDADSplot(index,anal_num,Project.Test_Item.Run.Channel(index).Analysis(anal_num).Type,XScale,YScale);
    end % switch print_data_type
    % Generate the print files for the Analysis only OR Time History only plots
    if (index == print_chan_start) && (print_data_type ~= 3)
        PlotHandle = gcf;
        eval(['print ''' pdfpathname pdffilename(1:end-3) 'ps'' -dpsc -f' num2str(PlotHandle)])
    else
        PlotHandle = gcf;
        eval(['print ''' pdfpathname pdffilename(1:end-3) 'ps'' -dpsc -append -f' num2str(PlotHandle)])
    end
    close %close figure
end % for index = print_chan_start:print_chan_end
% Convert the Postscript file to a PDF file
 ps2pdf('psfile', [pdfpathname pdffilename(1:end-3), 'ps'], 'pdffile', [pdfpathname pdffilename])
%  eval(['!cd C:\Progra~1\gs\gs8.54\lib & '...
%      'path %path%;C:\Progra~1\gs\gs8.54\bin;C:\Progra~1\gs\gs8.54\lib; & '...
%      'ps2pdf "' pdfpathname pdffilename(1:end-3) 'ps" "' pdfpathname pdffilename '"'])
% Delete the Postscript file
delete([pdfpathname pdffilename(1:end-3) 'ps']);

% =========================================================================
% function varargout = file_select_submenu_Callback(h, eventdata, handles, varargin)
% popupver006;

% =========================================================================
function varargout = file_exit_submenu_Callback(h, eventdata, handles, varargin)
delete(handles.figure1);
% Clear all variables before leaving the application
clear

% =========================================================================
function varargout = modify_range_menu_Callback(h, eventdata, handles, varargin)

% =========================================================================
function varargout = modify_mouse_submenu_Callback(h, eventdata, handles, varargin)
global Project;
if handles.type == 1
    SampleRate = Project.Test_Item.Run.Sample_Rate;
    tp = ginput(2);
    first = round(tp(1,1) * SampleRate) + 1;
    last = round(tp(2,1) * SampleRate) +1;
    if first > last
        tmpvar = first;
        first = last;
        last = tmpvar;
    end
    handles.first = first; 
    handles.last = last; 
    guidata(h, handles); % Save the changes
    plot_onscreen_timehistory(h, eventdata, handles, varargin)
end
if handles.type == 2;
    errordlg('Can Not Modify Range of PSD');
end
    
% =========================================================================
function varargout = modify_keyboard_submenu_Callback(h, eventdata, handles, varargin)
global Project;
if handles.type == 1
    SampleRate = Project.Test_Item.Run.Sample_Rate;
    prompt = {'Start Time:', 'Stop Time:'};
    dlgTitle = 'Modify Time Range';
    lineNo = [1 20; 1 20];
    newlimits = inputdlg(prompt, dlgTitle, lineNo);
    firsttime = str2num(newlimits{1,1});
    lasttime = str2num(newlimits{2,1});
    first = round(firsttime * SampleRate) + 1;
    last = round(lasttime * SampleRate);
    if first > last
        tmpvar = first;
        first = last;
        last = tmpvar;
    end
    
    handles.first = first; 
    handles.last = last; 

    plot_onscreen_timehistory(h, eventdata, handles, varargin)
end

if handles.type == 2;
   errordlg('Can Not Modify Range of PSD');
end

% =========================================================================
function settings_menu_Callback(h, eventdata, handles)
% hObject    handle to settings_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% =========================================================================
function settings_defaults_submenu_Callback(h, eventdata, handles)
% hObject    handle to settings_defaults_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Defaults_v001;

% =========================================================================
function varargout = choose_plot(h, eventdata, handles, varargin)
switch handles.type
	case 1
		plot_onscreen_timehistory(h, eventdata, handles, varargin);
   case 2
		plot_onscreen_PSD(h, eventdata, handles, varargin);
	case 3
		plot_onscreen_FRF(h, eventdata, handles, varargin);
	case 4
		plot_onscreen_sine(h, eventdata, handles, varargin);
	case 5
		plot_onscreen_Sine_FRF(h, eventdata, handles, varargin);
	case 6
		plot_onscreen_shockmag(h, eventdata, handles, varargin);
	case 7
		plot_onscreen_Octave(h, eventdata, handles, varargin);
end % switch handles.type
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_timehistory(h, eventdata, handles, varargin)
global Project;
%Determine channel # being displayed from shell
tmpstr = num2str(handles.chan);
%Start process of labeling display - Channel No. #
xlab = strcat('Channel No.',tmpstr);
%Get data from structure relative to shell time segment
x = Project.Test_Item.Run.Time_Ref(handles.first:handles.last);
y = Project.Test_Item.Run.Channel(handles.chan).Time_His(handles.first:handles.last);
plot(x,y), grid on;
%Finalize titles and labels
title(strcat('Time History: ', Project.Test_Item.Run.Descrip));
% xlabel(strcat(xlab,' - ',Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
xlabel(strcat(xlab,' :  ',Project.Test_Item.Run.Channel(handles.chan).Coordinate, ...
    Project.Test_Item.Run.Channel(handles.chan).Direction, ...
    Project.Test_Item.Run.Channel(handles.chan).Orientation, ...
    ' :  ', Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
% Determine Engineering Unit of Displayed data
dataEU = Project.Test_Item.Run.Channel(handles.chan).EU;
ylab = make_EU_name(handles);
ylabel(strcat(ylab,'(',dataEU,')'));
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_PSD(h, eventdata, handles, varargin)
global Project;
%Determine channel # being displayed from shell
tmpstr = num2str(handles.chan);
%Start process of labeling display - Channel No. #
xlab = strcat('Channel No.',tmpstr);
%Get data from structure using last analysis completed
latest = length(Project.Test_Item.Run.Channel(handles.chan).Analysis);
x = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Abs;
y = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord;
% Set Y-Axis Max Scale
ymax = max(abs(y));
ce = ceil(log10(ymax));
ymax = 10^(ce+1);
ymin = 10^(ce - 5);
xmax = Project.Test_Item.Run.Low_Pass;
LL = length(x);
xmax = ceil(x(LL));
loglog(x,y), grid on; axis([x(1) xmax ymin ymax]);
%Finalize titles and labels
title(strcat(Project.Test_Item.Run.Descrip,'-Power Spectral Density'));
xlabel(strcat(xlab,' :  ',Project.Test_Item.Run.Channel(handles.chan).Coordinate, ...
    Project.Test_Item.Run.Channel(handles.chan).Direction, ...
    Project.Test_Item.Run.Channel(handles.chan).Orientation, ...
    ' :  ', Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
% Determine Engineering Unit of Displayed data
dataEU = Project.Test_Item.Run.Channel(handles.chan).EU;
ylab = make_EU_name(handles);
ylabel(strcat('(',ylab,'(',dataEU,'))^2/Hz'));
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_FRF(h, eventdata, handles, varargin)
global Project;
tmpstr = num2str(handles.chan);
%xlab = 'Channel No ';
xlab = strcat('Channel No.',tmpstr);
%Get data from structure using last analysis completed
latest = length(Project.Test_Item.Run.Channel(handles.chan).Analysis);
x = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Abs;
y = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord;
% Set Y-Axis Max Scale
ymax = max(abs(y));
ce = ceil(log10(ymax));
ymax = 10^(ce+1);
ymin = 10^(ce - 5);
xmax = Project.Test_Item.Run.Low_Pass;
loglog(x,abs(y)), grid on; axis([x(1) xmax ymin ymax]);
%Finalize Title and labels
title(strcat(Project.Test_Item.Run.Descrip,'-Transfer Function: Magnitude'));
xlabel(strcat(xlab,'-',Project.Test_Item.Run.Channel(handles.chan).Trans_Loc,'/',Project.Test_Item.Run.Channel(handles.ref_chan).Trans_Loc));
ylabel('dB');
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_Octave(h, eventdata, handles, varargin)
global Project;
tmpstr = num2str(handles.chan);
xlab = strcat('Channel No.',tmpstr);
%Get data from structure using last analysis completed
latest = length(Project.Test_Item.Run.Channel(handles.chan).Analysis);
x = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Abs;
y = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord;
K = length(x);
H = bar(y);
Y_Min = fix(min(y) * 0.1) * 10.0;
ax = axis;
axis([0 K+1 Y_Min ax(4)]);
% axis([0 K+1 ax(3) ax(4)]);
ticks = find(x > 0);
set(gca,'XTick',ticks); 		% Label frequency axis.
%set(gca,'XTickLabels',F(ticks));         % MATLAB 4.1
set(gca,'XTickLabel',x(ticks)); 	% MATLAB 5.1
title(strcat(Project.Test_Item.Run.Descrip,'-1/3 Octave Analysis: dB'));
xlabel(strcat(xlab,' :  ',Project.Test_Item.Run.Channel(handles.chan).Coordinate, ...
    Project.Test_Item.Run.Channel(handles.chan).Direction, ...
    Project.Test_Item.Run.Channel(handles.chan).Orientation, ...
    ' :  ', Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
ylabel('dB');

guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_sine(h, eventdata, handles, varargin)
global Project;
%Determine channel # being displayed from shell
tmpstr = num2str(handles.chan);
%Start process of labeling display - Channel No. #
xlab = strcat('Channel No.',tmpstr);
%Get data from structure using last analysis completed
latest = length(Project.Test_Item.Run.Channel(handles.chan).Analysis);
x = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Abs;
y = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord;
ymax = max(abs(y));
ce = ceil(log10(ymax));
ymax = 10^(ce+1);
ymin = 10^(ce - 5);
xmax = x(length(x));
% loglog(x,abs(y)), grid on; axis([20 xmax ymin ymax]);
if (x(1) < xmax) % This was a sweep up
    loglog(x,abs(y)), grid on; axis([x(1) xmax ymin ymax]);
else % This was a sweep down
    loglog(x,abs(y)), grid on; axis([xmax x(1) ymin ymax]);
end
%Finalize titles and labels
title(strcat(Project.Test_Item.Run.Descrip,'-Swept Sine'));
xlabel(strcat(xlab,' :  ',Project.Test_Item.Run.Channel(handles.chan).Coordinate, ...
    Project.Test_Item.Run.Channel(handles.chan).Direction, ...
    Project.Test_Item.Run.Channel(handles.chan).Orientation, ...
    ' :  ', Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
% Determine Engineering Unit of Displayed data
dataEU = Project.Test_Item.Run.Channel(handles.chan).EU;
ylab = make_EU_name(handles);
ylabel(strcat(ylab,'(',dataEU,')'));
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_Sine_FRF(h, eventdata, handles, varargin)
global Project;
%Determine channel # being displayed from shell
tmpstr = num2str(handles.chan);
%Start process of labeling display - Channel No. #
xlab = strcat('Channel No.',tmpstr);
%Get data from structure using last analysis completed
latest = length(Project.Test_Item.Run.Channel(handles.chan).Analysis);
x = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Abs;
y = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord;
xmax = Project.Test_Item.Run.Low_Pass;
% ymax = max(abs(Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord));
ymax = max(abs(y));
ce = ceil(log10(ymax));
ymax = 10^(ce+1);
ymin = 10^(ce - 5);
loglog(x,abs(y)), grid on; axis([x(1) xmax ymin ymax]);
%Finalize titles and labels
title(strcat(Project.Test_Item.Run.Descrip,'-Swept Sine'));
xlabel(strcat(xlab,'-',Project.Test_Item.Run.Channel(handles.chan).Trans_Loc,'/',Project.Test_Item.Run.Channel(handles.ref_chan).Trans_Loc));
% xlabel(strcat(xlab,'-',Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
% Determine Engineering Unit of Displayed data
% dataEU = Project.Test_Item.Run.Channel(handles.chan).EU;
% ylab = make_EU_name(handles);
% ylabel(strcat(ylab,'(',dataEU,')'));
guidata(h, handles); % Save the changes

% =========================================================================
function varargout = plot_onscreen_shockmag(h, eventdata, handles, varargin)
global Project;
%Determine channel # being displayed from shell
tmpstr = num2str(handles.chan);
%Start process of labeling display - Channel No. #
xlab = strcat('Channel No.',tmpstr);
%Get data from structure using last analysis completed
latest = length(Project.Test_Item.Run.Channel(handles.chan).Analysis);
x = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Abs;
y = Project.Test_Item.Run.Channel(handles.chan).Analysis(latest).Ord;
xmax = Project.Test_Item.Run.Low_Pass;
ymax = max(abs(y));
ce = ceil(log10(ymax));
ymax = 10^(ce+1);
ymin = 10^(ce - 5);
loglog(x,abs(y)), grid on; axis([x(1) xmax ymin ymax]);
%Finalize titles and labels
title(strcat(Project.Test_Item.Run.Descrip,'-Shock Magnitude'));
xlabel(strcat(xlab,' :  ',Project.Test_Item.Run.Channel(handles.chan).Coordinate, ...
    Project.Test_Item.Run.Channel(handles.chan).Direction, ...
    Project.Test_Item.Run.Channel(handles.chan).Orientation, ...
    ' :  ', Project.Test_Item.Run.Channel(handles.chan).Trans_Loc));
% Determine Engineering Unit of Displayed data
dataEU = Project.Test_Item.Run.Channel(handles.chan).EU;
ylab = make_EU_name(handles);
ylabel(strcat(ylab,'(',dataEU,')'));
guidata(h, handles); % Save the changes

% =========================================================================
function eu_name = make_EU_name(handles)
global Project;
dataEU = upper(Project.Test_Item.Run.Channel(handles.chan).EU);
switch dataEU
    case{'G'}
        eu_name = 'Acceleration';
    case{'UE', 'US'}
        eu_name = 'Strain';
    case{'LBS','LB'}
        eu_name = 'Force';
    case{'V', 'VT', 'VLTS', 'VOLTS', 'VLT'}
        eu_name = 'Volts';
    case{'PSI'}
        eu_name = 'Sound Pressure Level';
    case{'IN-LBS', 'IN-LB'}
        eu_name = 'Moment';
    case{'DEG', 'DEGREES'}
        eu_name = 'Phase';
    case{'IN/S', 'IPS'};
        eu_name = 'Velocity';
    case{'IN/SEC/SEC'};
        eu_name = 'Acceleration';
    case{'IN'};
        eu_name = 'Displacement';
    otherwise
        eu_name = 'Unknown Units';
end

% =========================================================================
function prt_rtn = local_print_info
%entire function call be eliminated when GDADSplot in fully used
%create new figure
figure('MenuBar', 'none', 'Visible', 'on')
set(gcf, 'PaperPosition', [.5, .5, 10, 7.5], 'PaperOrientation', 'landscape');
h = axes('Position',[0 0 1 1], 'Visible','off');
axes('Position',[.1 .25 .8 .65])

% =========================================================================
function varargout = figure1_ResizeFcn(h, eventdata, handles, varargin)

% =========================================================================
function varargout = listbox2_Callback(h, eventdata, handles, varargin)

% =========================================================================
function CurrentDataset = Dataset(handles)
global Project;
%Determine Available Analysis index to save Data to.
try
	n = length(Project.Test_Item.Run.Channel(1).Analysis);
	n = n + 1;
catch
	n = 1;
end
CurrentDataset = n;

% =========================================================================
% --- Executes on button press in Accept Data.
function StoreData_Callback(hObject, eventdata, handles)
global Project;
%ask for Analysis Description
prompt = {'Description: (Analysis Type, Level, Start and Stop Times)'};
dlgTitle = 'Analysis Description';
lineNo = [1 60];
settings = inputdlg(prompt, dlgTitle, lineNo);
dataset = handles.CurrentDataset;
for i = 1:Project.Test_Item.Run.Num_Chan
    Project.Test_Item.Run.Channel(i).Analysis(dataset).Descrip = settings{1,1};
end
% Advance DataSet index
handles.CurrentDataset = Dataset(handles);
guidata(hObject, handles); % Save the changes

% =========================================================================
function export_menu_Callback(hObject, eventdata, handles)
% hObject    handle to export_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% =========================================================================
function export_unv_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to export_unv_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%  This function will export processed data out of the Project...Analysis
%  substructure into an ascii file with the universal file dataset 58 format.
[num_rec] = analysis2unv;

% =========================================================================
function export_excel_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to export_excel_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%  This function will export processed data out of the Project...Analysis
%  substructure into an Excel spreadsheet file.
[nchan] = analysis2xls;

% =========================================================================
function Data_Export_Processed_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to Data_Export_Processed_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% =========================================================================
function Data_Export_TimeHistory_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to Data_Export_TimeHistory_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% =========================================================================
function TimeHistory_to_UNV_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to TimeHistory_to_UNV_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%  This function will export processed data out of the Project...Analysis
%  substructure into an ascii file with the universal file dataset 58 format.
thist2unv(handles.first,handles.last);

% =========================================================================
function TimeHistory_to_XLS_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to TimeHistory_to_XLS_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%  This function will export processed data out of the Project...Analysis
%  substructure into an Excel spreadsheet file.
global Project;
thist2xls(handles.first,handles.last);

% =========================================================================
function varargout = info_menu_Callback(h, eventdata, handles, varargin)

% =========================================================================
function varargout = info_timehistory_submenu_Callback(h, eventdata, handles, varargin)
project_info;

% =========================================================================
function varargout = info_analysis_submenu_Callback(h, eventdata, handles, varargin)
analysis_info;

% =========================================================================
function varargout = DataEval_pushbutton_Callback(h, eventdata, handles, varargin)
global Project;
% Prompt for evaluation start and stop times
[start_time,stop_time] = eval_time_select;
% Index the start and stop times
fpoint = round(start_time * Project.Test_Item.Run.Sample_Rate)+1;
lpoint = round(stop_time * Project.Test_Item.Run.Sample_Rate)+1;
% Calculate statistics for each channel
for i = 1:Project.Test_Item.Run.Num_Chan
    channum(i) = i;
    dataeu(i) = {Project.Test_Item.Run.Channel(i).EU};
    data = Project.Test_Item.Run.Channel(i).Time_His(fpoint:lpoint);
    datamax(i) = max(data); % +Peak
    datamin(i) = min(data); % -Peak
    datastd(i) = std(data);
    datarms(i) = norm(data)/sqrt(length(data)); % RMS
    dataavg(i) = mean(data);
    acdata = data - dataavg(i);
    acmax(i) = max(abs(acdata)); %Peak  -  6/7/08: now taking max of ABS
    acrms(i) = norm(acdata)/sqrt(length(acdata)); % AC RMS
    pktorms(i) = acmax(i)/acrms(i); % Peak/RMS
    datacrest(i) = crest(data); % Crest
    dataskew(i) = skewness(data); % Skew
    datakurt(i) = kurtosis(data); % Kurt
    respnam{i} = [Project.Test_Item.Run.Channel(i).Coordinate ...
                           Project.Test_Item.Run.Channel(i).Direction ...
                           Project.Test_Item.Run.Channel(i).Orientation];
end
data1 = [channum.' datamax.' datamin.' datarms.' dataavg.' acmax.' datastd.'];
data2 = [pktorms.' datacrest.' dataskew.' datakurt.'];
labels = {'Chan #','+Peak','-Peak','RMS','Avg','Peak','AC RMS','EU','Peak/RMS','Crest','Skew','Kurt','Coord.'};
% Open Excel, add workbook, change active worksheet, 
% get/put array, save.
% First, open an Excel Server.
Excel = actxserver('Excel.Application');
% Make Excel visible
set(Excel, 'Visible', 1);
% Insert a new workbook.
Workbooks = Excel.Workbooks;
Workbook = invoke(Workbooks, 'Add');
% Make the first sheet active.
Sheets = Excel.ActiveWorkBook.Sheets;
sheet1 = get(Sheets, 'Item', 1);
invoke(sheet1, 'Activate');
% Get a handle to the active sheet.
Activesheet = Excel.Activesheet;
% Fill in header information
ActivesheetRange = get(Activesheet,'Range','A1','A1');
set(ActivesheetRange, 'Value', Project.Name);
ActivesheetRange = get(Activesheet,'Range','A2','A2');
set(ActivesheetRange, 'Value', Project.Test_Item.Run.Descrip);
ActivesheetRange = get(Activesheet,'Range','A3','A3');
set(ActivesheetRange, 'Value', ['Evaluation Start Time: ' num2str(start_time)...
        ' sec      Evaluation Stop Time: ' num2str(stop_time) ' sec']);
% Fill in column labels
ActivesheetRange = get(Activesheet,'Range','A5','M5');
set(ActivesheetRange, 'Value', labels);
% Fill in data
ActivesheetRange = get(Activesheet,'Range','A6',['G' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'Value', data1);
ActivesheetRange = get(Activesheet,'Range','H6',['H' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'Value', dataeu.');
ActivesheetRange = get(Activesheet,'Range','I6',['L' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'Value', data2);
ActivesheetRange = get(Activesheet,'Range','M6',['M' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'Value', respnam.');
% Format the spreadsheet
ActivesheetRange = get(Activesheet,'Range','A6',['A' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'ColumnWidth', 6);
ActivesheetRange = get(Activesheet,'Range','B6',['G' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'ColumnWidth', 8);
set(ActivesheetRange, 'NumberFormat','0.0000');
ActivesheetRange = get(Activesheet,'Range','H6',['H' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'ColumnWidth', 6);
ActivesheetRange = get(Activesheet,'Range','I6',['L' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'ColumnWidth', 10);
set(ActivesheetRange, 'NumberFormat','0.0000');
ActivesheetRange = get(Activesheet,'Range','A5',['M' num2str(Project.Test_Item.Run.Num_Chan+5)]);
set(ActivesheetRange, 'HorizontalAlignment',3) % Center values in cells
% xlswrite(eval,head,labels);

% =========================================================================
function TimeHistory_to_ATI_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to TimeHistory_to_ATI_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
thist2ati(handles.first,handles.last);

% =========================================================================
function Anal_Only_Proj_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to Anal_Only_Proj_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global Project;
Project_AnalOnly = Project;
% Clear contents of Time Reference vector and Time History vector for all
% channels
Project_AnalOnly.Test_Item.Run.Time_Ref = [];
for i=1:Project_AnalOnly.Test_Item.Run.Num_Chan
    Project_AnalOnly.Test_Item.Run.Channel(i).Time_His = [];
end
% Prompt for filename to save new Project structure to
[filename,pathname] = uiputfile('*.mat','Select New Project File');
if isequal([filename, pathname], [0,0])
    return
end
if exist('pathname')~=1
    pathname = '';
end
File = fullfile(pathname, filename);
% Save new Project structure to selected file
save(File, 'Project_AnalOnly');
clear Project_AnalOnly;
% Call function that will rename the variable name in the new Project file
RenameProjectVariable(File);

% =========================================================================
function RenameProjectVariable(filename)
% This function will read in Project structure .mat file that has the time
% history data stripped out of it and rename the variable so it can be read in
% by other standard routines.
load(filename);
Project = Project_AnalOnly;
save(filename, 'Project');


% --------------------------------------------------------------------
function File_menu_SaveAs_V6_Callback(hObject, eventdata, handles)
% hObject    handle to File_menu_SaveAs_V6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global Project;
pathname = handles.pathname;
% Save the Current Directory
CurDir = pwd;
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to original data directory
% Remove the last '\'
pathname(length(pathname)) = '';
% Change every '\' to an escape sequence '\\'
filepath = strrep(pathname,'\','\\');
% Construct the cd command 
filepath = ['cd ' '''' filepath ''''];
eval(filepath);
%- - - - - - - - - - - - - - - - - - - - - - - -
% - - - From Dan Worth's code - - -
[filename, pathname] = uiputfile('*.mat', 'MATLAB Data Files');
if isequal([filename, pathname], [0,0])
    disp('File not found')
else
    File = fullfile(pathname, filename);
    save( File, 'Project', '-v6');
end
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to Current Directory
% Change every '\' to an escape sequence '\\'
CurrentPath = strrep(CurDir,'\','\\');
% Construct the cd command 
CurrentPath = ['cd ' '''' CurrentPath ''''];
eval(CurrentPath);

% --------------------------------------------------------------------
% function file_convert_DataFlex_submenu_Callback(hObject, eventdata, handles)
% hObject    handle to file_convert_DataFlex_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

function file_convert_DataFlex_submenu_Callback(hObject, eventdata, handles, varargin)
% hObject    handle to file_convert_DataMAX_submenu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global Project;
Project = EmptyProj;
% pack;
%- - - - - - - - - - - - - - - - - - - - - - - -
% Change position to C:\Data directory
filepath = 'C:\\Data';
% Construct the cd command 
filepath = ['cd ' '''' filepath ''''];
eval(filepath);
[filename, pathname] = uigetfile('*.datx_index', 'DataFlex Index Files');
if isequal([filename, pathname], [0,0])
    return
else
    fullname = fullfile(pathname,filename);
    handles.pathname = pathname;
    File = fullname;
    Project = ImportDATXindex( File );
end

% Modifed on 20-Dec-2013 by CMcLeod to extract keywords from the DATX Index File
[ProjectName, TI_Name, WD, Axis, TestType, TestLevel, RunNum, Description] = ReadKeywords(fullname);

% Assign the parameters for Analysis Description
prompt = {'Project Name', 'Test Item', 'WD', 'Run Axis', 'Test Type', 'Test Level', 'Run Number', 'Run Description','Remove DC Offset'};
dlgTitle = 'Test Info';
lineNo = [1 60; 1 60; 1 12; 1 4; 1 12; 1 15; 1 12; 1 60; 1 30];

defAns{1,1} = ProjectName;
defAns{1,2} = TI_Name;
defAns{1,3} = WD;
defAns{1,4} = Axis;
defAns{1,5} = TestType;
defAns{1,6} = TestLevel;
defAns{1,7} = RunNum;
defAns{1,8} = Description;
defAns{1,9} = 'YES';

Ans = inputdlg(prompt, dlgTitle, lineNo, defAns);
Project.Name = Ans{1,1};
Project.Test_Item.TI_Name = Ans{2,1};
Project.Test_Item.WD = str2double(Ans{3,1});
Project.Test_Item.Run.Axis = Ans{4,1};
Project.Test_Item.Run.Test_Type = Ans{5,1};
Project.Test_Item.Run.Test_Level = Ans{6,1};
Project.Test_Item.Run.Run_Num = str2double(Ans{7,1});
Project.Test_Item.Run.Descrip = Ans{8,1};

if (strcmp(upper(Ans{9,1}), 'YES')) || (strcmp(upper(Ans{9,1}), 'Y'))
    % remove offset
    for index = 1:Project.Test_Item.Run.Num_Chan
        Project.Test_Item.Run.Channel(index).Time_His = double(Project.Test_Item.Run.Channel(index).Time_His);
        Project.Test_Item.Run.Channel(index).Time_His = ...
         Project.Test_Item.Run.Channel(index).Time_His - mean(Project.Test_Item.Run.Channel(index).Time_His);
        Project.Test_Item.Run.Channel(index).Time_His = single(Project.Test_Item.Run.Channel(index).Time_His);
    end
else
   fprintf('DC not removed\n');
end

    %Adjust channels from DataFelex recorder in control room 09Sept13 for
    %Peak Current Shutdown event
    % RescaleRecorder;
    
handles.type = 1;
handles.first = 1;
handles.last  = size(Project.Test_Item.Run.Time_Ref,2);
guidata(hObject, handles); % Save the changes
%Determine next available Dataset
handles.CurrentDataset = Dataset(handles);
guidata(hObject, handles); % Save the changes
first_chan_pushbutton_Callback(hObject, eventdata, handles, varargin);
